﻿using System;
using System.Collections.Generic;
using System.Configuration;
using System.Data;
using System.Data.SqlClient;
using System.Linq;
using System.Linq.Expressions;
using System.Text;
using System.Threading.Tasks;
using YmtAuth.Domain.Model.LoginAuth;
using YmtAuth.Domain.Repository;
using YmtAuth.Repository.Mongodb;
using YmtSystem.CrossCutting;

namespace YmtAuth.Repository.YmtAuthDomainRepository
{
    public class UserLoginBillsRepository : Repository_v1<UserLoginBill, string>, IUserLoginBillsRepository
    {
        public UserLoginBillsRepository()
            : base(new DbContext("BillsMongoUrl"))
        {

        }

        private static readonly string UpdateUserLockedSQL = @"declare @t table(id int)
insert into @t 
select tb1.col.value('@v','int') from @xml.nodes('/root/k') tb1(col)
update u  set u.bLocked=@Locked 
from Ymt_Users as  u
inner join @t  as t
on 
u.iUserId=t.id";

        private static readonly string userlockInfoSQL = @"declare @t table(id int)
insert into @t 
select tb1.col.value('@v','int') from @xml.nodes('/root/k') tb1(col)
select UserId,[Description], OperateTime  from UserLockedLog b 
inner join
@t t
on b.UserID=t.id";
        public int SetUserBillsSQLLockedStatus(int[] userid, int locked)
        {
            using (var conn = new SqlConnection(ConfigurationManager.ConnectionStrings["YmatouUserConnectionString"].ConnectionString))
            {
                try
                {
                    conn.Open();
                    var command = conn.CreateCommand();
                    command.CommandType = CommandType.Text;
                    command.CommandText = UpdateUserLockedSQL;
                    command.Parameters.Clear();
                    command.Parameters.AddWithValue("@Locked", locked);
                    var val = new SqlParameter("@xml", SqlDbType.Xml);
                    val.Value = ParseArrayValue(userid);
                    command.Parameters.Add(val);
                    return command.ExecuteNonQuery();
                }
                catch (SqlException ex)
                {
                    YmatouLoggingService.Error("SetUserBillsSQLLockedStatus SqlException {0}", ex);
                    return ex.ErrorCode;
                }
                catch (Exception e)
                {
                    YmatouLoggingService.Error("SetUserBillsSQLLockedStatus Exception {0}", e);
                    return 0;
                }
            }
        }

        private string ParseArrayValue(int[] value)
        {
            var str=new StringBuilder("<root>");
            foreach (var val in value)
            {
                str.Append("<k v='").Append(val).Append("'/>");
            }
            str.Append("</root>");
            return str.ToString();
        }

        public IEnumerable<Tuple<int, string>> FindUserLockdInfo(int[] userid)
        {
            var list=new List<Tuple<int,string>>();
            using (var conn =new SqlConnection(
                        ConfigurationManager.ConnectionStrings["UserLockedLog"].ConnectionString))
            {
                conn.Open();
                var command= conn.CreateCommand();
                command.CommandText = userlockInfoSQL;
                command.CommandType= CommandType.Text;
                command.Parameters.Clear();
                var val = new SqlParameter("@xml", SqlDbType.Xml);
                val.Value = ParseArrayValue(userid);
                command.Parameters.Add(val);
                var reader = command.ExecuteReader();
                while (reader!=null && reader.Read())
                {
                    var tmpuserid =reader.IsDBNull(0)?0: Convert.ToInt32(reader["UserId"]);
                    var desc = reader.IsDBNull(1) ? string.Empty : reader["Description"].ToString();
                    var tuple = Tuple.Create(tmpuserid, desc);
                    list.Add(tuple);
                }
            }
            return list;
        }
    }
}
